package com.neo.tiny.bpm.flowable.listener;

import com.google.common.collect.ImmutableSet;
import com.neo.tiny.bpm.service.task.BpmProcessInstanceExtService;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.delegate.event.FlowableCancelledEvent;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @Description: 监听 {@link ProcessInstance} 的开始与完成，创建与更新对应的 {@link com.neo.tiny.bpm.entity.BpmProcessInstanceExtDO} 记录
 * @Author: yqz
 * @CreateDate: 2022/10/8 23:32
 */
@Component
public class BpmProcessInstanceEventListener extends AbstractFlowableEngineEventListener {

    /**
     * TODO 解决循环依赖
     */
    @Lazy
    @Autowired
    private BpmProcessInstanceExtService processInstanceExtService;

    public static final Set<FlowableEngineEventType> PROCESS_INSTANCE_EVENTS = ImmutableSet.<FlowableEngineEventType>builder()
            .add(FlowableEngineEventType.PROCESS_CREATED)
            .add(FlowableEngineEventType.PROCESS_CANCELLED)
            .add(FlowableEngineEventType.PROCESS_COMPLETED)
            .build();

    public BpmProcessInstanceEventListener() {
        super(PROCESS_INSTANCE_EVENTS);
    }

    @Override
    protected void processCreated(FlowableEngineEntityEvent event) {
        processInstanceExtService.createProcessInstanceExt((ProcessInstance) event.getEntity());
    }

    @Override
    protected void processCancelled(FlowableCancelledEvent event) {
        processInstanceExtService.updateProcessInstanceExtCancel(event);
    }

    @Override
    protected void processCompleted(FlowableEngineEntityEvent event) {
        processInstanceExtService.updateProcessInstanceExtComplete((ProcessInstance) event.getEntity());
    }
}
